package net.linlan.plat.comm.security.handle;

import com.alibaba.fastjson.JSON;
import net.linlan.commons.core.ObjectUtils;
import net.linlan.commons.core.ResponseResult;
import net.linlan.frame.FrameAdminUser;
import net.linlan.plat.comm.manager.AsyncManager;
import net.linlan.plat.comm.manager.factory.AsyncFactory;
import net.linlan.plat.comm.service.TokenService;
import net.linlan.utils.MessageUtils;
import net.linlan.utils.ServletUtils;
import net.linlan.utils.constant.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 * 
 * @author Linlan
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{
    @Autowired
    private TokenService tokenService;

    /**
     * 退出处理
     * @param request   请求
     * @param response  响应
     * @param authentication    权限验证
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException
    {
        FrameAdminUser loginUser = tokenService.getLoginUser(request);
        if (ObjectUtils.isNotEmpty(loginUser))
        {
            String username = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            AsyncManager.me().execute(AsyncFactory.saveAdminLoginLog(loginUser.getAdminId(), username, Constants.LOGOUT, MessageUtils.message("user.logout.success"), loginUser.getAppId()));
        }
        ServletUtils.renderString(response, JSON.toJSONString(ResponseResult.ok(MessageUtils.message("user.logout.success"))));
    }
}
